import { useIntervalFn, useDebounceFn } from "@vueuse/core";
import { ref } from "vue";
import axios from "axios";

export default function useStart(fn: () => void) {
	// 状态
	const loading = ref(false);
	const resetLoading = ref(false);

	// 时间
	const monitorBeginTime = ref(0);
	const monitorDuration = ref(0);

	/**
	 * 重置监测时间
	 */
	const resetBeginTime = () => {
		monitorBeginTime.value = Date.now();
		monitorDuration.value = 0;
	};

	/**
	 * 计算持续时间
	 */
	const computeDuration = () => {
		monitorDuration.value = Date.now() - monitorBeginTime.value;
	};

	// 防抖 请求数据
	const debouncedFn = useDebounceFn(
		() => {
			fn();
		},
		2000,
		{ maxWait: 3000 }
	);

	/**
	 * 执行监测
	 */
	const { pause, resume, isActive } = useIntervalFn(
		() => {
			computeDuration();
			debouncedFn();
		},
		1000,
		{
			immediate: false,
		}
	);

	// 开始监测
	const onStart = () => {
		loading.value = true;

		setTimeout(async () => {
			if (isActive.value) {
				pause();
			} else {
				await axios.get("/api/alarms/start");
				resetBeginTime();
				resume();
			}
			loading.value = false;
		}, 200);
	};

	/**
	 * 恢复所有 alarm
	 */
	const onReset = async () => {
		resetLoading.value = true;
		await axios.get("/api/alarms/reset");
		fn();
		resetLoading.value = false;
	};

	return {
		loading,
		running: isActive,
		onStart,
		resetLoading,
		onReset,
		monitorDuration,
	};
}
